package com.qlzb.taskmanagement.utils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import com.qlzb.taskmanagement.pojo.OutputWrapper;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName VerifyUtils
 * @Description TODO    数据校验 工具类
 * @Authr 袁聪
 * @Date 2018/6/1 15:04
 * @Version v2.0
 */
public class VerifyUtils {


    /**
     * 获取验证结果集中的错误信息（Controller层调用）
     * @param bindingResult 错误信息结果集
     * @return              错误信息
     */
    public static OutputWrapper getBindingResultInfo(BindingResult bindingResult){
        List<ObjectError> list = bindingResult.getAllErrors();
        List<String> errorsList = new ArrayList<>();

        for (ObjectError error : list){
            errorsList.add(error.getDefaultMessage());
        }

        Map<String, List> errorsMap = new HashMap<>();
        errorsMap.put("errors",errorsList);

        return OutputWrapper.markParamError(errorsMap);
    }


    /**
     * 对传入对象进行验证(Service层调用)
     * @param o 验证对象
     * @return  验证结果
     */
    public static OutputWrapper validate(Object o){
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        Validator validator = vf.getValidator();
        Set<ConstraintViolation<Object>> set = validator.validate(o);

        List<String> errorsList = new ArrayList<>();

        for (ConstraintViolation<Object> constraintViolation : set) {
            errorsList.add(constraintViolation.getPropertyPath()+":"+constraintViolation.getMessage());
        }

        if (errorsList.size() > 0){
            Map<String, List> errorsMap = new HashMap<>();
            errorsMap.put("errors",errorsList);

            return OutputWrapper.markParamError(errorsMap);
        }

        return OutputWrapper.markParamRight();
    }


    /**
     * 验证后的错误信息格式
     * @param outputWrapper    异常信息结果集
     * @return                  指定格式的结果集
     */
    public static OutputWrapper errorInfoFormat(OutputWrapper outputWrapper){
        List<String> errorsList = new ArrayList<>();
        errorsList.add(outputWrapper.getMessage());
        Map<String, List> errorsMap = new HashMap<>();
        errorsMap.put("errors",errorsList);
        outputWrapper.setData(errorsMap);

        return outputWrapper;
    }



}
